package com.pojoin.system.service.impl;

import com.pojoin.system.dao.UserDao;
import com.pojoin.system.domain.UserDO;
import com.pojoin.system.service.MoneyHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.pojoin.system.dao.TradeDao;
import com.pojoin.system.domain.TradeDO;
import com.pojoin.system.service.TradeService;
import org.springframework.transaction.annotation.Transactional;


@Service
public class TradeServiceImpl implements TradeService {
	@Autowired
	private TradeDao tradeDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private MoneyHistoryService moneyHistoryService;
	
	@Override
	public TradeDO get(Long id){
		return tradeDao.get(id);
	}
	
	@Override
	public List<TradeDO> list(Map<String, Object> map){
		return tradeDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return tradeDao.count(map);
	}
	
	@Override
	//@Transactional(rollbackFor = Exception.class)
	public int save(TradeDO trade){
		trade.setCreatTime(new Date());
		//1:转入；2：转出
		trade.setStatus("2");
		userDao.updateMoney(-trade.getMoney(),trade.getUserId());
		userDao.updateMoney(trade.getMoney(),trade.getTouserId());
		tradeDao.save(trade);
		trade.setStatus("1");
		UserDO userDO = userDao.get(Long.valueOf(trade.getUserId()));
		UserDO toUser = userDao.get(Long.valueOf(trade.getTouserId()));
		moneyHistoryService.addMoney(userDO.getUserId(), -Double.valueOf(trade.getMoney()), 0d, toUser.getUserId(), "转出", "m", userDO.getMoney().toString(), userDO.getBalance().toString());
		moneyHistoryService.addMoney(toUser.getUserId(), Double.valueOf(trade.getMoney()), 0d, userDO.getUserId(), "转入", "m", toUser.getMoney().toString(), toUser.getBalance().toString());
		return tradeDao.save(trade);
	}
	
	@Override
	public int update(TradeDO trade){
		return tradeDao.update(trade);
	}
	
	@Override
	public int remove(Long id){
		return tradeDao.remove(id);
	}
	
	@Override
	public int batchRemove(Long[] ids){
		return tradeDao.batchRemove(ids);
	}

	@Override
	public List<Map<String, Object>> listHoutai(Map<String, Object> params) {
		return tradeDao.listHoutai(params);
	}

	@Override
	public int countHoutai(Map<String, Object> params) {
		return tradeDao.count(params);
	}

}
